package com.zzhrtech.wgzx_cityzen.ui.me;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.beans.disease.RoleListBean;
import com.zzhrtech.wgzx_cityzen.beans.me.AllCountBean;
import com.zzhrtech.wgzx_cityzen.beans.me.ItemCountBean;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChartActivity extends BaseActivity implements OnChartValueSelectedListener, OnDateSetListener {

//    private BarChart mChart;
    private PieChart mChart;

    private static final String[] m={"一周内","一月内","一年内","所有"};
    List<RoleListBean.Data> depList;
    private Spinner spinner2;
    private TextView tv_starttime,tv_endtime;

    private LinearLayout layout_list;
    private TimePickerDialog timePickerDialog;

    private String startTime = "",endTime=  "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);

        toolbar.setNavigationIcon(R.mipmap.ic_close);
        initView();

        timePickerDialog = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId("时间选择")
                .setThemeColor(getResources().getColor(R.color.colorPrimary))
                .setCallBack(this)
                .build();

        httpGetDep();
    }
    private void initView() {
        mChart = (PieChart) findViewById(R.id.chart_count);
        layout_list = (LinearLayout) findViewById(R.id.layout_list);


        spinner2 = (Spinner) findViewById(R.id.spinner2);

        tv_starttime = (TextView) findViewById(R.id.tv_starttime);
        tv_endtime = (TextView) findViewById(R.id.tv_endtime);

        tv_starttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                timePickerDialog.show(getSupportFragmentManager(),"start");
            }
        });

        tv_endtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                timePickerDialog.show(getSupportFragmentManager(),"end");
            }
        });

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
                    httpGetAllCount();
                }else {
                    httpGetItemCount(depList.get(position-1).getDep_id());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });



        //转换成 %
        mChart.setUsePercentValues(true);
        mChart.setDescription("");
        mChart.setExtraOffsets(5, 10, 5, 5);

        //摩擦力
        mChart.setDragDecelerationFrictionCoef(0.95f);

        mChart.setCenterText(generateCenterSpannableText());

        ///
        mChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        mChart.setDrawHoleEnabled(true);
        mChart.setHoleColor(Color.WHITE);

        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(110);

        mChart.setHoleRadius(58f);
        mChart.setTransparentCircleRadius(61f);

        mChart.setDrawCenterText(true);

        mChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        mChart.setRotationEnabled(true);
        mChart.setHighlightPerTapEnabled(true);

        /////


        //中心为空
//        mChart.setDrawHoleEnabled(true);
//        mChart.setHoleColor(Color.WHITE);
//
//        mChart.setTransparentCircleColor(Color.WHITE);
//        mChart.setTransparentCircleAlpha(110);
//
//        mChart.setHoleRadius(58f);
//        mChart.setTransparentCircleRadius(61f);
//
//        mChart.setDrawCenterText(true);
//
//        //能否转动
//        mChart.setRotationAngle(0);
//        // enable rotation of the chart by touch
//        mChart.setRotationEnabled(true);
//        mChart.setHighlightPerTapEnabled(true);

        // mChart.setUnit(" €");
        // mChart.setDrawUnitsInChart(true);

        // add a selection listener
        mChart.setOnChartValueSelectedListener(this);

//        setData(4, 100);

        mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        Legend l = mChart.getLegend();
        l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        // entry label styling
        mChart.setEntryLabelColor(Color.BLACK);
        mChart.setEntryLabelTextSize(13f);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 0){

                depList = (List<RoleListBean.Data>) msg.obj;
                String[] dataitem = new String[depList.size() + 1];
                dataitem[0] = "总览";
                for (int i = 0;i<depList.size();i++){
                    dataitem[i + 1] = depList.get(i).getDep_name();
                }
                ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(ChartActivity.this,android.R.layout.simple_spinner_item,dataitem);

                //设置下拉列表的风格
                adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                //将adapter 添加到spinner中
                spinner2.setAdapter(adapter2);

            }else if (msg.what == 1){

                Bundle bundle = msg.getData();

                List<AllCountBean.Data> list = (List<AllCountBean.Data>) bundle.getSerializable("list");

                setData(list,null);
                setList(list,null);

                Log.d("size==11========",list.get(1).getNum() + "");
            }else if (msg.what == 2){
                List<ItemCountBean.Data> list = (List<ItemCountBean.Data>) msg.obj;
                setData(null,list);
                setList(null,list);

                Log.d("size==========",list.get(0).getCount() + "");
            }

            return false;
        }
    });

    //获得部门列表
    private void httpGetDep(){
        GsonRequest<RoleListBean> gsonRequest = new GsonRequest<RoleListBean>(com.android.volley.Request.Method.GET, Constans.HTTP_GETDepartList, RoleListBean.class, null, new com.android.volley.Response.Listener<RoleListBean>() {
            @Override
            public void onResponse(RoleListBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    //获得部门列表
    private void httpGetItemCount(String depid){
        Map<String,String> params = new HashMap<String, String>();
        params.put("dep_id",depid);
        params.put("start",startTime);
        params.put("end",endTime);

        GsonRequest<ItemCountBean> gsonRequest = new GsonRequest<ItemCountBean>(Request.Method.POST, Constans.HTTP_GETITEMCOUNT, ItemCountBean.class, params, new com.android.volley.Response.Listener<ItemCountBean>() {
            @Override
            public void onResponse(ItemCountBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 2;
                   message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void httpGetAllCount(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("start",startTime);
        params.put("end",endTime);

        Log.d("par=====",params + "");
        GsonRequest<AllCountBean> gsonRequest = new GsonRequest<AllCountBean>(com.android.volley.Request.Method.POST, Constans.HTTP_GETALLCOUNT, AllCountBean.class, params, new com.android.volley.Response.Listener<AllCountBean>() {
            @Override
            public void onResponse(AllCountBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list",(Serializable) response.getData());
                    message.setData(bundle);
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void setData(List<AllCountBean.Data> list,List<ItemCountBean.Data> list1) {

//        float mult = range;

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.

        int count = list != null ? list.size() : list1.size();
        for (int i = 0; i < count ; i++) {
            String number = list != null ? list.get(i).getNum() : list1.get(i).getCount();
            String name = list != null ? list.get(i).getDep_name() : list1.get(i).getStatus();
            if (!number.equals("0"))
            entries.add(new PieEntry(Float.parseFloat(number), name));
        }

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        // dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        mChart.setData(data);

        // undo all highlights
        mChart.highlightValues(null);

        mChart.invalidate();
    }

    private void setList(List<AllCountBean.Data> list,List<ItemCountBean.Data> list1){
        layout_list.removeAllViews();

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        int count = list != null ? list.size() : list1.size();
        for (int i = 0; i < count;i++) {
            LinearLayout layout = new LinearLayout(this);
            layout.setOrientation(LinearLayout.HORIZONTAL);
            layout.setPadding(0,8,0,8);

            String title = list != null ? list.get(i).getDep_name() : list1.get(i).getStatus();
            TextView textView = new TextView(this);
            textView.setGravity(Gravity.CENTER);
            params.weight = 1;
            textView.setLayoutParams(params);
            textView.setText(title);
            layout.addView(textView);

            String number = list != null ? list.get(i).getNum() : list1.get(i).getCount();
            TextView textView1 = new TextView(this);
            textView1.setGravity(Gravity.CENTER);
            params.weight = 1;
            textView1.setLayoutParams(params);
            textView1.setText(number);
            layout.addView(textView1);

            layout_list.addView(layout);
        }



    }

    private SpannableString generateCenterSpannableText() {

//        SpannableString s = new SpannableString("统计数据");
//        s.setSpan(new RelativeSizeSpan(1.7f), 0, s.length(), 0);


        SpannableString s = new SpannableString("维管中心\n统计数据");
        s.setSpan(new RelativeSizeSpan(1.7f), 0, 4, 0);
//        s.setSpan(new StyleSpan(Typeface.NORMAL), 3, s.length(), 0);
//        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
//        s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), 4, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), 4, s.length(), 0);
        return s;
    }


    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {

        if (timePickerView.getTag().equals("start")){
            startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date(millseconds));
            tv_starttime.setText(startTime);
        }else {
            endTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date(millseconds));
            tv_endtime.setText(endTime);
            if (spinner2.getSelectedItemPosition() == 0){
                httpGetAllCount();
            }else {
                httpGetItemCount(depList.get(spinner2.getSelectedItemPosition() - 1).getDep_id());
            }
        }

    }
}
